import { t } from '@src/locales'
/* emum */
import TableNameEnum from '@model/enum/TableNameEnum';
/* scss */
import '@src/component/business/BizSelectColumn/BizSelectColumn.scss'
import './selectColumn.scss'
/* components */
import BizSelectColumnSort from '@src/component/business/BizSelectColumn/BizSelectColumnSort'
import iconChoose from './iconChoose';
/* service */
import { getFieldName, isSystemFiled } from '@service/FieldService'
/* util */
import _ from 'lodash'
import { typeOf } from '@src/util/assist'
import { isFunction, isObject } from '@src/util/type'
import {
    filterTreeWithKeywordHandler,
    convertDisplayNameToName,
    convertColumnWithSave,
    columnTreeToObject,
    upwardToggleChecked
} from '@src/component/business/BizSelectColumn/BizSelectColumnUtil'

import { TASK_GUIDE_SELECT_COLUMN } from '@src/component/guide/taskV2Store';
import { message } from '@src/util/message';

/** 
 * 顶部导航栏自定义配置
*/
const SelectColumn = {
    name: 'biz-select-column',
    props: {
        mode: {
            type: String,
            default: ''
        },
        storageKey: {
            type: String | Number,
            default: TASK_GUIDE_SELECT_COLUMN
        },
        validate: {
            type: Function
        },
        modalTitle: {
            type: String,
            default: t('common.base.choiceCol')
        },
        max: {
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            columnSortList: [],
            columnTree: {},
            originColumns: [],
            show: false,
            taskType: {},
            keyWord: '',
            originalkeyWord: '',
            isSearch: false,
            guideSelectColumn: false,
            columnTreeObject: {},
            isShowCustomLink: false, // 是否显示自定义链接弹窗
            customLinkForm: {
                name: '', // 链接名称
                url: '', // 链接地址
                icon: 'icon-caidan-liucheng', // 图标
            },
            rules: {
                name: [
                    { required: true, message: t('setting.enterprise.quickEntrance.tip2'), trigger: 'blur' }
                ],
                url: [
                    { required: true, message: t('setting.enterprise.quickEntrance.tip3'), trigger: 'blur' },
                    { type: 'url', message: t('common.util.validator.linkTip'), trigger: 'blur' }
                ]
            },
        }
    },
    computed: {
        columnFilterTree() {
            return this.keyWord ? filterTreeWithKeywordHandler(this.columnTree, this.keyWord) : this.columnTree
        }
    },
    methods: {
        /**
         * @description 排序字段删除事件
         * @param {Field} field 被删除的字段
         */
        onDeletedSortFieldItemHandler(field) {
            const fieldName = getFieldName(field)
            const canceledField = this.columnTreeObject[fieldName]
            // 找不到取消的字段对应的数据
            if (!canceledField) {
                return console.warn('Caused: canceledField is empty')
            }

            // 切换被取消字段的显示状态
            canceledField.show = false

            // 是否为系统字段
            const isSystem = isSystemFiled(field)
            // 处理系统字段选中状态 (临时处理方法)
            if (isSystem) {
                return this.unCheckedSystemFiled(field)
            }

            this.unCheckedAttributeField(field)
        },
        unCheckedAttributeField(field) {
            return this.unCheckedAttributeFields(false, field, this.columnFilterTree.system, this.columnFilterTree.system);
        },
        unCheckedAttributeFields(field, attributeTreeNode) {
            // 无系统字段树数据则返回
            if (!isObject(attributeTreeNode?.columns)) return

            // 处理自定义字段选中状态 (临时处理方法)
            for (let key in attributeTreeNode.columns) {
                this.checkboxFieldChange(
                    false,
                    field,
                    attributeTreeNode.columns[key],
                    attributeTreeNode
                )
            }
        },
        onChange(value) {
            this.originalkeyWord = value;
            this.onSearch()
        },
        // 重置
        reset() {
            this.originalkeyWord = '';
            this.keyWord = '';
            this.isSearch = false;

            upwardToggleChecked(this.columnFilterTree)
        },
        // 筛选
        onSearch() {
            this.keyWord = this.originalkeyWord;

            if (!this.keyWord) {
                return this.reset()
            }

            this.isSearch = true

            upwardToggleChecked(this.columnFilterTree)
        },
        buildSortLists(treeNode = {}) {
            let { columns } = treeNode;

            let isColumnsObject = this.isColumnsObject(columns)
            let lists = columns

            if (isColumnsObject) {
                lists = Object.keys(columns).map(key => {
                    return { name: columns[key].name, lists: this.buildSortLists(columns[key]) }
                })
            } else {
                lists = columns.filter(column => column?.show)
            }

            return lists
        },
        /** 
         * @description 列数据分组处理
         * 目前是按照 templateId 工单类型id 分组的
        */
        columnsDataGrouped(columns = []) {
            // 系统字段组
            let systemFieldsGroup = []
            // 自定义字段组
            let attributeFieldsGroup = {}
            // 公共字段组
            let commonFieldsGroup = []
            // 产品系统字段组
            let productSystemFieldsGroup = []
            // 产品自定义字段组
            let productAttributeFieldsGroup = []
            // 产品注册自定义字段组
            let productRegisterSystemFieldsGroup = []
            // 产品注册自定义字段组
            let productRegisterAttributeFieldsGroup = []
            // 产品类型系统字段组
            let catalogSystemFieldsGroup = []
            // 客户联系人系统字段组
            let customerContactSystemFieldsGroup = []
            // 产品类型自定义字段组
            let catalogAttributeFieldsGroup = []
            // 客户系统字段组
            let customerSystemFieldsGroup = []
            // 客户自定义字段组
            let customerAttributeFieldsGroup = []
            // 服务商字段
            let ServiceProviderFieldsGroup = []
            // 新增字段，没有会报错
            let customerContactAttributeFieldsGroup = []
            // 客户满意度字段组
            let customerSatisfactionFieldsGroup = {}
            // 在线客服系统字段组
            let imSystemFieldsGroup = []
            // 在线客服自定义字段组
            let imAttributeFieldsGroup = []
            // 合同管理系统字段组
            let contractSystemFieldsGroup = []
            // 合同管理自定义字段组
            let contractAttributeFieldsGroup = []
            // 在线支付字段组
            let paymentBillOnlineFieldsGroup = []
            // 服务商系统字段组
            let providerSystemFieldsGroup = []
            // 服务商自定义字段组
            let providerAttributeFieldsGroup = []
            // 工程师系统字段组
            let engineerSystemFieldsGroup = []
            // 工程师自定义字段组
            let engineerAttributeFieldsGroup = []
            // 项目管理系统字段
            let projectSystemFieldsGroup = []
            // 项目管理自定义字段
            let projectAttributeFieldsGroup = []
            // 智能计划任务明细系统字段
            let smartPlanDetailsSystemFieldsGroup = []
            // 智能计划任务明细自定义字段
            let smartPlanDetailsAttributeFieldsGroup = []

            columns.forEach((column, index) => {
                if (!column) return false

                // 是否是系统字段
                let isSystemFiled = !(column?.templateId)
                let isCommonFiled = column?.isCommon
                let isProductTable = column && column.tableName == 'product';
                let isProductRegisterTable = (column && column.tableName == 'productRegister') || this.isProductRegisterMode;
                let isCatalogTable = column && column.tableName == 'catalog';
                let isCustomerTable = column && column.tableName == 'customer';
                let isCustomerContactTable = column && column.tableName == 'customerContact';
                let isServiceProviderTable = column && column.tableName == 'serviceProvider';
                let isSatisfaction = column && column.tableName == 'satisfaction';
                let isImTable = column?.tableName == 'im';
                let isContractTable = column && column.tableName == 'contract';
                let isProvider = column?.tableName == 'provider';
                let isEngineer = column?.tableName == 'engineer'
                let isProject = column?.tableName == TableNameEnum.Project;
                let isSmartPlanDetails = column?.tableName == 'smartPlanDetails';
                if (isProductTable || isProductRegisterTable || isCatalogTable || isCustomerTable || isCustomerContactTable || isServiceProviderTable || isImTable || isContractTable || isProvider || isEngineer || isProject || isSmartPlanDetails) {
                    isSystemFiled = column?.isSystem

                    if (isSystemFiled) {
                        if (isProductTable) productSystemFieldsGroup.push(column)
                        else if (isProductRegisterTable) productRegisterSystemFieldsGroup.push(column)
                        else if (isCatalogTable) catalogSystemFieldsGroup.push(column)
                        else if (isCustomerTable) customerSystemFieldsGroup.push(column)
                        else if (isServiceProviderTable) ServiceProviderFieldsGroup.push(column)
                        else if (isImTable) imSystemFieldsGroup.push(column)
                        else if (isContractTable) contractSystemFieldsGroup.push(column)
                        else if (isProvider) providerSystemFieldsGroup.push(column)
                        else if (isEngineer) engineerSystemFieldsGroup.push(column)
                        else if (isProject) projectSystemFieldsGroup.push(column)
                        else if (isSmartPlanDetails) smartPlanDetailsSystemFieldsGroup.push(column)
                        else customerContactSystemFieldsGroup.push(column)
                    } else {
                        if (isProductTable) productAttributeFieldsGroup.push(column)
                        else if (isProductRegisterTable) productRegisterAttributeFieldsGroup.push(column)
                        else if (isCatalogTable) catalogAttributeFieldsGroup.push(column)
                        else if (isCustomerTable) customerAttributeFieldsGroup.push(column)
                        else if (isServiceProviderTable) ServiceProviderFieldsGroup.push(column)
                        else if (isImTable) imAttributeFieldsGroup.push(column)
                        else if (isContractTable) contractAttributeFieldsGroup.push(column)
                        else if (isProvider) providerAttributeFieldsGroup.push(column)
                        else if (isEngineer) engineerAttributeFieldsGroup.push(column)
                        else if (isProject) projectAttributeFieldsGroup.push(column)
                        else if (isSmartPlanDetails) smartPlanDetailsAttributeFieldsGroup.push(column)
                        else customerContactAttributeFieldsGroup.push(column)
                    }

                } else {
                    if (isCommonFiled) {
                        commonFieldsGroup.push(column)
                    } else
                        if (this.isPaymentBillOnline) {
                            paymentBillOnlineFieldsGroup.push(column)
                        } else
                            if (isSystemFiled) {
                                systemFieldsGroup.push(column)
                            } else
                                if (isSatisfaction) {
                                    let { templateName, templateId } = column
                                    templateName = this.getTemplateName(templateId) || templateName
                                    if (!customerSatisfactionFieldsGroup[templateId]) {
                                        customerSatisfactionFieldsGroup[templateId] = { name: templateName, columns: [] }
                                    }

                                    column.templateName = templateName
                                    customerSatisfactionFieldsGroup[templateId].columns.push(column)
                                }
                                else {
                                    // 按工单类型分组 ( 工单类型是不可以重名的，所以可以用 工单类型名字 为 key )
                                    let { templateName, templateId } = column
                                    templateName = this.getTemplateName(templateId) || templateName
                                    // 判断是否 自定义字段组存在 此类型数据
                                    if (!attributeFieldsGroup[templateId]) {
                                        attributeFieldsGroup[templateId] = { name: templateName, columns: [] }
                                    }

                                    column.templateName = templateName
                                    attributeFieldsGroup[templateId].columns.push(column)
                                }
                }

            })

            // 字段树🌲
            let columnsTree = {
                system: { name: t('common.form.fieldGroupName.system'), columns: systemFieldsGroup, checked: false, root: true, toggle: true },
                attribute: { name: t('common.form.fieldGroupName.attribute'), columns: attributeFieldsGroup, checked: false, root: true, toggle: true },
                productSystem: { name: t('common.form.fieldGroupName.productSystem'), columns: productSystemFieldsGroup, checked: false, root: true, toggle: true },
                productAttribute: { name: t('common.form.fieldGroupName.productAttribute'), columns: productAttributeFieldsGroup, checked: false, root: true, toggle: true },
                productRegisterSystem: { name: t('common.form.fieldGroupName.productRegisterSystem'), columns: productRegisterSystemFieldsGroup, checked: false, root: true, toggle: true },
                productRegisterAttribute: { name: t('common.form.fieldGroupName.productRegisterAttribute'), columns: productRegisterAttributeFieldsGroup, checked: false, root: true, toggle: true },
                catalogSystem: { name: t('common.form.fieldGroupName.catalogSystem'), columns: catalogSystemFieldsGroup, checked: false, root: true, toggle: true },
                catalogAttribute: { name: t('common.form.fieldGroupName.catalogAttribute'), columns: catalogAttributeFieldsGroup, checked: false, root: true, toggle: true },
                customerSystem: { name: t('common.form.fieldGroupName.customerSystem'), columns: customerSystemFieldsGroup, checked: false, root: true, toggle: true },
                customerAttribute: { name: t('common.form.fieldGroupName.customerAttribute'), columns: customerAttributeFieldsGroup, checked: false, root: true, toggle: true },
                customerContactSystem: { name: t('common.form.fieldGroupName.customerContactSystem'), columns: customerContactSystemFieldsGroup, checked: false, root: true, toggle: true },
                customerContactAttribute: { name: t('common.form.fieldGroupName.customerContactAttribute'), columns: customerContactAttributeFieldsGroup, checked: false, root: true, toggle: true },
                serviceProvider: { name: t('common.form.fieldGroupName.serviceProvider'), columns: ServiceProviderFieldsGroup, checked: false, root: true, toggle: true },
                common: { name: t('common.form.fieldGroupName.common'), columns: commonFieldsGroup, checked: false, root: true, toggle: true },
                customerSatisfaction: { name: t('common.form.fieldGroupName.customerSatisfaction'), columns: customerSatisfactionFieldsGroup, checked: false, root: true, toggle: true },
                imSystem: { name: t('common.form.fieldGroupName.imSystem'), columns: imSystemFieldsGroup, checked: false, root: true, toggle: true },
                imAttribute: { name: t('common.form.fieldGroupName.imAttribute'), columns: imAttributeFieldsGroup, checked: false, root: true, toggle: true },
                contractSystem: { name: t('common.form.fieldGroupName.contractSystem'), columns: contractSystemFieldsGroup, checked: false, root: true, toggle: true },
                contractAttribute: { name: t('common.form.fieldGroupName.contractAttribute'), columns: contractAttributeFieldsGroup, checked: false, root: true, toggle: true },
                paymentBillOnlineSystem: { name: t('common.form.fieldGroupName.paymentBillOnlineSystem'), columns: paymentBillOnlineFieldsGroup, checked: false, root: true, toggle: true },
                providerSystem: { name: t('common.form.fieldGroupName.providerSystem'), columns: providerSystemFieldsGroup, checked: false, root: true, toggle: true },
                providerAttribute: { name: t('common.form.fieldGroupName.providerAttribute'), columns: providerAttributeFieldsGroup, checked: false, root: true, toggle: true },
                engineerSystem: { name: t('common.form.fieldGroupName.engineerSystem'), columns: engineerSystemFieldsGroup, checked: false, root: true, toggle: true },
                engineerAttribute: { name: t('common.form.fieldGroupName.engineerAttribute'), columns: engineerAttributeFieldsGroup, checked: false, root: true, toggle: true },
                projectSystem: { name: t('common.form.fieldGroupName.system'), columns: projectSystemFieldsGroup, checked: false, root: true, toggle: true },
                projectAttribute: { name: t('common.form.fieldGroupName.attribute'), columns: projectAttributeFieldsGroup, checked: false, root: true, toggle: true },
                smartPlanDetailsSystem: { name: t('common.form.fieldGroupName.system'), columns: smartPlanDetailsSystemFieldsGroup, checked: false, root: true, toggle: true },
                smartPlanDetailsAttribute: { name: t('common.form.fieldGroupName.attribute'), columns: smartPlanDetailsAttributeFieldsGroup, checked: false, root: true, toggle: true },
            }

            if (Object.keys(columnsTree.attribute.columns).length == 0) {
                delete columnsTree.attribute
            }

            // 初始化选中
            for (let key in columnsTree) {
                if (Object.keys(columnsTree[key].columns).length == 0) {
                    delete columnsTree[key]
                    continue
                }
                this.toggleTreeChecked(columnsTree[key])
            }

            this.initColumnSortList(columns)

            return columnsTree
        },
        /** 
         * @description 关闭设置窗 
        */
        close() {
            this.columnTree = {} //  清除缓存
            this.show = false
        },
        /** 
         * @description 字段复选框 变化
        */
        checkboxFieldChange(value, field, parent, parentOfParent) {
            if (value && this.max != 0 && this.columnSortList.length >= this.max) {
                return message.error(`最多选择${this.max}个字段`)
            }
            field.show = value;
            if (!value) { field.fixLeft = false }
            // 判断当前父级下的子级是否全选
            const isCheckedAll = parent.columns.every(column => column?.show)
            parent.checked = isCheckedAll

            // 判断如果父级全选，则去寻找父级的兄弟层级，进而判断 父父级的状态
            if (isCheckedAll) {
                // 判断父父级的是否是对象
                let isObjectChildren = this.isColumnsObject(parentOfParent.columns)
                let isParentOfParentChecdAll = true;

                if (isObjectChildren) {
                    for (let key in parentOfParent.columns) {
                        let child = parentOfParent.columns[key];
                        if (!child) {
                            isParentOfParentChecdAll = false;
                            break;
                        }
                    }

                    parentOfParent.checked = isParentOfParentChecdAll;
                }
            } else {
                parentOfParent.checked = false;
            }

            this.columnFieldChangeWithSort(value, field, parent)
        },
        /** 
         * @description 父级复选框 变化
        */
        checkboxParentChange(value, treeNode, parent) {
            treeNode.checked = value;
            // 全选
            if (value) {
                this.toggleCheckedWithDown(treeNode, true)
                this.toggleCheckedWithUp(treeNode, parent)
            } else {
                this.toggleCheckedWithDown(treeNode)
                this.toggleCheckedWithUp(treeNode, parent)
            }

            this.columnParentChangeWithSort(value, treeNode, parent)
        },
        /** 
         * @description 字段复选框 变化 排序
        */
        columnFieldChangeWithSort(checked, field, parent) {
            let isParentRoot = parent.root
            let sortList = this.columnSortList.slice()

            if (isParentRoot && checked) {
                return this.columnSortList.push(convertDisplayNameToName(field))
            }

            if (isParentRoot && !checked) {
                this.columnSortList = sortList.filter(item => item.fieldName != field.fieldName)
                return
            }

            this.columnSortListMerge(checked, field, parent, sortList);
        },
        /** 
         * @description 获取字段排序列表下 子分类
        */
        columnSortListGetGroup(sortList, parent) {
            let templateGroup = {}
            let templateIndex = -1

            for (let i = 0; i < sortList.length; i++) {
                let item = sortList[i]
                if (item.name == parent.name) {
                    templateGroup = item
                    templateIndex = i
                    break
                }
            }

            return { templateGroup, templateIndex }
        },
        /** 
         * @description 字段排序列表合并
        */
        columnSortListMerge(checked, field, parent, sortList) {
            let { templateGroup = {}, templateIndex } = this.columnSortListGetGroup(sortList, parent)
            let templateColumns = templateGroup.lists || []

            checked
                ? templateColumns.push(convertDisplayNameToName(field))
                : templateColumns = templateColumns.filter(item => item.fieldName != field.fieldName)

            // 未找到类型
            templateIndex == -1
                ? this.columnSortList.push({ name: parent.name, lists: [convertDisplayNameToName(field)] })
                : this.$set(this.columnSortList, templateIndex, { ...templateGroup, lists: templateColumns })
        },
        /** 
         * @description 字段排序列表添加字段列
        */
        columnSortListFieldPush(columns, sortList) {
            columns.forEach(column => {
                let isHave = sortList.some(list => list.fieldName == column?.fieldName)
                if (!isHave) {
                    sortList.push(convertDisplayNameToName(column))
                }
            })
        },
        /** 
         * @description 父级复选框 变化排序
        */
        columnParentChangeWithSort(checked, treeNode, parent) {
            let isTreeNodeRoot = treeNode.root
            let sortList = _.cloneDeep(this.columnSortList)
            let isColumnsObject = this.isColumnsObject(treeNode.columns)

            // eslint-disable-next-line no-empty
            if (isTreeNodeRoot && isColumnsObject) {
                if (checked) {
                    for (let key in treeNode.columns) {
                        let item = treeNode.columns[key]
                        let { templateGroup = {}, templateIndex } = this.columnSortListGetGroup(sortList, item)

                        let isFindedTemplate = templateIndex >= 0
                        templateIndex = isFindedTemplate ? templateIndex : sortList.length

                        isFindedTemplate
                            ? this.columnSortListFieldPush(item.columns, templateGroup.lists)
                            : templateGroup.lists = this.buildSortLists(item)

                        sortList[templateIndex] = {
                            name: item.name,
                            lists: templateGroup.lists
                        }
                    }
                } else {
                    sortList = sortList.filter(item => !Array.isArray(item.lists))
                }
            }
            else if (isTreeNodeRoot && !isColumnsObject) {
                if (checked) {
                    let lists = this.buildSortLists(treeNode);
                    this.columnSortListFieldPush(lists, sortList)
                } else {
                    let treeNodeColumns = treeNode?.columns || []
                    sortList = sortList.filter(item => {
                        return treeNodeColumns.every(treeNodeColumn => treeNodeColumn.fieldName !== item.fieldName)
                    })
                }
            }
            else {
                if (checked) {
                    let templateIndex = sortList.findIndex(item => item.name == treeNode.name)
                    templateIndex <= -1 ? templateIndex = sortList.length : null

                    sortList[templateIndex] = {
                        name: treeNode.name,
                        lists: this.buildSortLists(treeNode)
                    }
                } else {
                    sortList = sortList.filter(item => item.name != treeNode.name)
                }
            }


            this.columnSortList = sortList
        },
        getTemplateName(templateId) {
            let { taskType } = this

            if (templateId == taskType.id) return taskType.name

            return null
        },
        /** 
         * @description 初始化排序列表
        */
        initColumnSortList(originColumns) {
            const TemplateMap = {}
            let sortList = []

            originColumns.filter(column => column && column?.show).forEach((column, index) => {
                let isSystemFiled = !(column?.templateId)
                let isCommonFiled = column?.isCommon

                // 系统字段直接添加至 根级
                if (isSystemFiled || isCommonFiled) {
                    return sortList.push(convertDisplayNameToName(column))
                }

                let { templateId, templateName } = column
                let templateData = TemplateMap[templateId]
                if (!templateData) {
                    TemplateMap[templateId] = { index, name: templateName, columns: [] }
                }

                TemplateMap[templateId].columns.push(convertDisplayNameToName(column))
            })

            for (let key in TemplateMap) {
                let { columns, index, name } = TemplateMap[key]
                sortList.splice(index, 0, {
                    name,
                    lists: columns
                })
            }

            this.columnSortList = sortList
        },
        /** 
         * @description 列数据 是否是 对象
        */
        isColumnsObject(columns) {
            return typeOf(columns) === 'object'
        },
        /** 
         * @description 显示 设置窗
        */
        open(columns, taskType) {
            this.keyWord = '';
            this.originalkeyWord = ''
            this.isSearch = false;
            this.originColumns = _.cloneDeep(columns)
            this.taskType = taskType
            this.columnTree = this.columnsDataGrouped(this.originColumns);
            this.show = true
            this.columnTreeObject = columnTreeToObject(this.columnTree)
        },
        /** 
         * @description 渲染字段
        */
        renderField(field = {}, parent = {}, parentOfParent = {}) {
            const show = field.show === 'important' ? true : field.show
            if (field.type == 'customLink') return null;
            return (
                <div class="biz-select-column-field" >
                    <el-checkbox value={show} disabled={field.show === 'important'} label={field.displayName} onInput={value => this.checkboxFieldChange(value, field, parent, parentOfParent)}>
                        <span class="biz-select-column-field-content">{field.displayName}</span>
                    </el-checkbox>
                </div>
            )
        },
        openCustomLink() {
            // 清空表单与校验
            this.$refs.customLink.clearValidate();
            this.customLinkForm = {
                name: '', // 链接名称
                url: '', // 链接地址
                icon: 'icon-caidan-liucheng', // 图标
            }
            this.isShowCustomLink = true;
        },
        closeCustomLink() {
            this.isShowCustomLink = false;
        },
        createCustomLink() {
            this.$refs.customLink.validate((valid) => {
                if (valid) {
                    this.columnSortList.push({
                        checked: true,
                        displayName: this.customLinkForm.name,
                        fieldName: 'customLink' + new Date().getTime(),
                        url: this.customLinkForm.url,
                        name: this.customLinkForm.name,
                        icon: this.customLinkForm.icon,
                        root: false,
                        show: true,
                        type: 'customLink',
                    });
                    this.isShowCustomLink = false;
                } 
            });
        },
        updateCustomLinkName(value) {
            console.log('hbc ~ updateCustomLinkName ~ value:', value)
            this.customLinkForm.name = value;
        },
        updateCustomLinkUrl(value) {
            this.customLinkForm.url = value;
        },
        updateCustomLinkIcon(value) {
            this.customLinkForm.icon = value;
        },
        /** 
         * @description 渲染树节点
        */
        renderTreeNode(treeNode = {}, parent = {}) {
            let isHaveChildren = Array.isArray(treeNode.columns)
            let isRoot = treeNode.root
            let isToggle = isRoot ? treeNode.toggle : true
            return (
                <div class="biz-select-column-tree-parent">
                    {
                        isToggle && (
                            <transition name="slide-down">
                                <div class={`biz-select-column-tree-child ${isRoot ? 'biz-select-column-tree-firstchild' : 'biz-select-column-tree-twochild'}`}
                                    style={{ margin: 0 }}
                                >
                                    {
                                        isHaveChildren
                                            ? treeNode.columns.map(column => this.renderField(column, treeNode, parent))
                                            : treeNode.columns && Object.keys(treeNode.columns).map(key => this.renderTreeNode(treeNode.columns[key], treeNode))
                                    }
                                </div>
                            </transition>
                        )
                    }
                </div>
            )
        },
        /** 
         * @description 渲染树 Document Object Model
        */
        renderTreeDom(h) {
            let tree = this.columnFilterTree;

            const TreeDom = Object.keys(tree).map(treeKey => {
                return (
                    this.renderTreeNode(tree[treeKey], tree[treeKey])
                )
            })

            return TreeDom
        },
        /**
         * @description 保存
        */
        save() {
            if (isFunction(this.validate)) {

                const validated = this.validate(this.columnSortList)

                if (!validated) {
                    console.warn('请检查 validate 方法, 是否校验通过')
                    return
                }

            }

            let columns = [];
            this.columnSortList.forEach(column => {
                if (Array.isArray(column.lists)) {
                    column.lists.forEach(item => {
                        columns.push(convertColumnWithSave(item))
                    })
                } else {
                    columns.push(convertColumnWithSave(column))
                }
            })

            let columnMap = columns.reduce((acc, column) => (acc[column.fieldName] = column) && acc, {});

            this.originColumns.forEach(originColumn => {
                if (!originColumn) return false

                let { fieldName } = originColumn
                let sortColumn = columnMap[fieldName]
                if (!sortColumn) {
                    if (originColumn.show !== 'important') originColumn.show = false;
                    columns.push(originColumn)
                }

            })

            this.close();
            this.$emit('save', {
                type: 'column',
                data: columns
            });
        },
        /** 
         * @description 向下 -> 切换 是否选中
        */
        toggleCheckedWithDown(treeNode, checked = false) {
            let isColumnsObject = this.isColumnsObject(treeNode.columns);

            if (isColumnsObject) {
                for (let key in treeNode.columns) {
                    this.toggleCheckedWithDown(treeNode.columns[key], checked);
                }
            } else {
                treeNode.checked = checked
                treeNode.columns.forEach(column => {
                    if (column.show == 'important') return // show = 'important' disabled，遇到此类checkbox则不做选中处理
                    column.show = checked
                });
            }

        },
        /** 
         * @description 向上 -> 切换 是否选中
        */
        toggleCheckedWithUp(treeNode, parent) {
            // 根级
            if (treeNode.root) return

            let isColumnsObject = this.isColumnsObject(parent.columns);
            let isChildAllChecked = false;

            if (isColumnsObject) {
                for (let key in parent.columns) {
                    let column = parent.columns[key]
                    isChildAllChecked = Boolean(column?.checked)

                    if (!isChildAllChecked) break;
                }

                parent.checked = isChildAllChecked;
            }
        },
        /** 
         * @description 切换树的选中
        */
        toggleTreeChecked(treeNode) {
            let isColumnsObject = this.isColumnsObject(treeNode.columns);
            let checked = false;

            if (isColumnsObject) {
                checked = Object.keys(treeNode.columns).every(key => this.toggleTreeChecked(treeNode.columns[key]))
            } else {
                checked = treeNode.columns.every(column => column?.show)
            }

            treeNode.checked = checked

            return checked
        },
        formRender() {
            return h('el-form', {
                ref: 'customLink',
                props: {
                    rules: this.rules,
                    model: this.customLinkForm
                }
            }, [
                h('el-form-item', {
                    props: {
                        label: t('common.base.name'),
                        prop: 'name'
                    }
                }, [
                    h('el-input', {
                        on: {
                            input: this.updateCustomLinkName
                        },
                        attrs: {
                            placeholder: t('common.placeholder.input2'),
                        },
                        props: {
                            value: this.customLinkForm.name
                        },
                        attrs: {
                            placeholder: t('common.placeholder.input2')
                        },
                    })
                ]),
                h('el-form-item', {
                    props: {
                        label: t('common.base.link'),
                        prop: 'url',
                    },
                }, [
                    h('span', {
                        slot: 'label',
                    }, [
                        h('span', {}, t('common.base.link')),
                        h('i', {
                            class: 'iconfont icon-question-circle',
                        })
                    ]),
                    h('el-input', {
                        on: {
                            input: this.updateCustomLinkUrl
                        },
                        attrs: {
                            placeholder: t('setting.enterprise.quickEntrance.customLink.linkPlaceholder')
                        },
                        props: {
                            value: this.customLinkForm.url
                        },
                        attrs: {
                            placeholder: t('setting.enterprise.quickEntrance.tip1')
                        },
                    }),
                ]),
            ])
        },
    },
    render(h) {
        return (
            <div>
                <base-modal
                    appendToBody={true}
                    class="biz-select-column-modal"
                    title={this.modalTitle}
                    show={this.show}
                    onClose={this.close}
                    width="500px"
                >
                    <div class="biz-select-column-main">
                        <div class="biz-select-column-box">
                            <div
                                class={`biz-select-column-body`}
                            >
                                <div class="bbx-biz-select-column-tree-title">
                                    {t('setting.enterprise.quickEntrance.title1')}
                                    {
                                        this.max != 0 ?
                                            <span> ({this.columnSortList.length}/{this.max})</span>
                                            : ''
                                    }
                                </div>
                                <div class="biz-select-column-item">{this.renderTreeDom(h)}</div>
                            </div>
                            <div style="position: relative; flex:1;margin-left: 24px;">
                                {/* 新人引导 start*/}
                                <div id="guide-test"></div>
                                {/* 新人引导 end*/}
                                <biz-select-column-sort
                                    lists={this.columnSortList}
                                    onDelete={field => this.onDeletedSortFieldItemHandler(field)}
                                >
                                    <div
                                        slot="title"
                                        class="biz-select-column-sort-title"
                                        id="guide-test-dom"
                                    >
                                        <span class="biz-select-column-sort-title-text">
                                            {t('setting.enterprise.quickEntrance.title2')}
                                        </span>
                                    </div>
                                </biz-select-column-sort>
                            </div>
                        </div>
                    </div>

                    <template slot="footer">
                        <el-button onClick={this.close}>{t('common.base.close')}</el-button>
                        <el-button onClick={this.openCustomLink}>{t('setting.enterprise.quickEntrance.customLink.title')}</el-button>
                        <el-button type="primary" onClick={this.save}>
                            {t('common.base.save')}
                        </el-button>
                    </template>

                </base-modal>
                <base-modal
                    appendToBody={true}
                    class="custom-link-modal"
                    title={t('setting.enterprise.quickEntrance.customLink.title')}
                    show={this.isShowCustomLink}
                    onClose={() => { this.isShowCustomLink = false }}
                    width="536px"
                >
                    <div class="modal-title">
                        <div>{t('setting.enterprise.quickEntrance.customLink.tip')}</div>
                    </div>
                    {this.formRender()}
                    <div style="margin:5px 0 5px 0">{t('setting.enterprise.quickEntrance.customLink.icon')}</div>
                    <iconChoose onInput={this.updateCustomLinkIcon} value={this.customLinkForm.icon}/>
                    <template slot="footer">
                        <el-button onClick={this.closeCustomLink}>{t('common.base.cancel')}</el-button>
                        <el-button type="primary" onClick={this.createCustomLink}>{t('common.base.create3')}</el-button>
                    </template>
                </base-modal>
            </div>
        )
    },
    components: {
        [BizSelectColumnSort.name]: BizSelectColumnSort,
        iconChoose,
    }
}

export default SelectColumn;